﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using MyOS.Models;
using MyOS.Utils;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;

namespace MyOS.Views
{
    public partial class CreateSystemView : UserControl
    {
        //private BindingExpression bindExpression;
        private readonly MainWindow.Feedback feedback;

        public CreateSystemView(MainWindow.Feedback feedback)
        {
            InitializeComponent();
            TextBoxSystemName.Text = "MyOperationSystem";
            TextBoxDiskC.Text = "4096";
            TextBoxDiskD.Text = "4096";
            var system = new SystemInfoItemModel();
            SystemInfo = system;
            DataContext = SystemInfo;
            this.feedback = feedback;
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (Convert.ToInt32(TextBoxDiskC.Text) < 4096 || Convert.ToInt32(TextBoxDiskD.Text) < 4096)
            {
                var result = MessageBoxX.Show("磁盘大小必须介于 4096-16384 Byte(4-16kB)之间。", "Error",
                    Application.Current.MainWindow, MessageBoxButton.YesNo, new MessageBoxXConfigurations
                    {
                        MessageBoxStyle = MessageBoxStyle.Modern,
                        MessageBoxIcon = MessageBoxIcon.Error,
                        ButtonBrush = "#FF4C4C".ToColor().ToBrush(),
                        NoButton = "为什么？",
                        YesButton = "好的"
                    });
                if (result == MessageBoxResult.No)
                    result = MessageBoxX.Show("模拟磁盘采用FAT表结构，每一个磁盘块为64Byte。" +
                                              "其中前N个磁盘块用来存储文件在磁盘中存储的磁盘块号（也就是FAT表）。" +
                                              "而磁盘块号在前两个分区中的存储是以Byte数组的形式存在的，用这8个bit" +
                                              "必须要能表示所有的磁盘号。" +
                                              "若为一个FAT，也就是可以存储64个Byte，也就是可以存储64个磁盘单元。" +
                                              "64*64=4096Byte；四个FAT可以存储64*4个Byte，可以存储256*64=16384Byte。",
                        "为什么有最小值最大值？",
                        Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations
                        {
                            MessageBoxStyle = MessageBoxStyle.Modern,
                            MessageBoxIcon = MessageBoxIcon.Info,
                            //ButtonBrush = "#FF4C4C".ToColor().ToBrush(),
                            MaxContentWidth = 500,
                            MaxContentHeight = 130,
                            MinHeight = 300,
                            FontSize = 18
                        });
            }
            else
            {
                CrlCustom.Index++;
                ProgressBarHelper.SetAnimateTo(Bar, Bar.Value += 20);
            }
        }

        private void Previous_Click(object sender, RoutedEventArgs e)
        {
            if (Convert.ToInt32(TextBoxDiskC.Text) < 4096 || Convert.ToInt32(TextBoxDiskD.Text) < 4096)
            {
                var result = MessageBoxX.Show("磁盘大小必须介于 4096-16384 Byte(4-16kB)之间。", "Error",
                    Application.Current.MainWindow, MessageBoxButton.YesNo, new MessageBoxXConfigurations
                    {
                        MessageBoxStyle = MessageBoxStyle.Modern,
                        MessageBoxIcon = MessageBoxIcon.Error,
                        ButtonBrush = "#FF4C4C".ToColor().ToBrush(),
                        NoButton = "为什么？",
                        YesButton = "好的"
                    });
                if (result == MessageBoxResult.No)
                    result = MessageBoxX.Show("模拟磁盘采用FAT表结构，每一个磁盘块为64Byte。" +
                                              "其中前N个磁盘块用来存储文件在磁盘中存储的磁盘块号（也就是FAT表）。" +
                                              "而磁盘块号在前两个分区中的存储是以Byte数组的形式存在的，用这8个bit" +
                                              "必须要能表示所有的磁盘号。" +
                                              "若为一个FAT，也就是可以存储64个Byte，也就是可以存储64个磁盘单元。" +
                                              "64*64=4096Byte；四个FAT可以存储64*4个Byte，可以存储256*64=16384Byte。",
                        "为什么有最小值最大值？",
                        Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations
                        {
                            MessageBoxStyle = MessageBoxStyle.Modern,
                            MessageBoxIcon = MessageBoxIcon.Info,
                            //ButtonBrush = "#FF4C4C".ToColor().ToBrush(),
                            MaxContentWidth = 500,
                            MaxContentHeight = 130,
                            MinHeight = 300,
                            FontSize = 18
                        });
            }
            else
            {
                CrlCustom.Index--;
                ProgressBarHelper.SetAnimateTo(Bar, Bar.Value -= 20);
            }
        }

        private void TextBoxDiskC_TextChanged(object sender, TextChangedEventArgs e)
        {
            {
                try
                {
                    var strNum = TextBoxDiskC.Text;
                    if ("" == strNum) return;

                    var num = int.Parse(TextBoxDiskC.Text);
                    TextBoxDiskC.Text = num.ToString();
                    if (num <= 16384)
                    {
                    }
                    else
                    {
                        TextBoxDiskC.Text = TextBoxDiskC.Text.Remove(3);
                        TextBoxDiskC.SelectionStart = TextBoxDiskC.Text.Length;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void TextBoxDiskC_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var re = new Regex("[^0-9-]+");

            e.Handled = re.IsMatch(e.Text);
        }

        private void TextBoxDiskC_KeyDown(object sender, KeyEventArgs e)
        {
            var txt = sender as TextBox;

            // 过滤按键
            if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
                e.Handled = false;
            else if (e.Key >= Key.D0 && e.Key <= Key.D9)
                e.Handled = false;
            else
                e.Handled = true;
        }

        private void SliderC_ValueChanged<T>(object sender, RoutedPropertyChangedEventArgs<T> e)
        {
            var value = SliderC.Value;
            TextBoxDiskC.Text = Convert.ToInt32(value).ToString();
        }

        private void SliderD_ValueChanged<T>(object sender, RoutedPropertyChangedEventArgs<T> e)
        {
            var value = SliderD.Value;
            TextBoxDiskD.Text = Convert.ToInt32(value).ToString();
        }

        private void Finish_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region 初始化磁盘文件创建

                var fileDiskC = new FileStream("./DiskC", FileMode.Create);
                var byteDiskCBytes = new byte[Convert.ToInt32(TextBoxDiskC.Text)];
                fileDiskC.Write(byteDiskCBytes);
                DiskUtils.setDbrForCreate(fileDiskC, 'C');
                fileDiskC.Close();
                var fileDiskD = new FileStream("./DiskD", FileMode.Create);
                var byteDiskDBytes = new byte[Convert.ToInt32(TextBoxDiskD.Text)];
                fileDiskD.Write(byteDiskDBytes);
                DiskUtils.setDbrForCreate(fileDiskD, 'D');
                fileDiskD.Close();
                Notice.Show("磁盘创建成功！", "完成！", 3, MessageBoxIcon.Success);

                #endregion

                //委托回调
                feedback.Invoke();
                //写入系统相关配置文件
                IniUtils.Write("System", "IsCreated", "1", "./config.ini");
                IniUtils.Write("System", "CreateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "./config.ini");
                IniUtils.Write("System", "SystemName", TextBoxSystemName.Text, "./config.ini");
            }
            catch (IOException exception)
            {
                var result = MessageBoxX.Show("创建磁盘失败。\r\n" + exception, "Error",
                    Application.Current.MainWindow, MessageBoxButton.YesNo, new MessageBoxXConfigurations
                    {
                        MessageBoxStyle = MessageBoxStyle.Modern,
                        MessageBoxIcon = MessageBoxIcon.Error,
                        ButtonBrush = "#FF4C4C".ToColor().ToBrush()
                    });

                throw;
            }
        }

        private void writeFATCount(FileStream diskFileStream)
        {
        }
    }
}